package org.jeecg.modules.system.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.entity.SysOperationLog;
import org.jeecg.modules.system.service.ISysOperationLogService;
import org.jeecg.modules.system.vo.SysOperationLogPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 操作日记
 * @Author: jeecg-boot
 * @Date:   2020-09-22
 * @Version: V1.0
 */
@Api(tags="操作日记")
@RestController
@RequestMapping("/xmss/sysOperationLog")
@Slf4j
public class SysOperationLogController {
	@Autowired
	private ISysOperationLogService sysOperationLogService;
	
	/**
	 * 分页列表查询
	 *
	 * @param sysOperationLog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "操作日记-分页列表查询")
	@ApiOperation(value="操作日记-分页列表查询", notes="操作日记-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SysOperationLog sysOperationLog,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		SysOperationLog sysOperationLogs =new  SysOperationLog();
		QueryWrapper<SysOperationLog> queryWrapper = QueryGenerator.initQueryWrapper(sysOperationLogs, req.getParameterMap());
		Page<SysOperationLog> page = new Page<SysOperationLog>(pageNo, pageSize);
		//姓名关键词
		String name = sysOperationLog.getUsername();
		if(oConvertUtils.isNotEmpty(name)) {
			queryWrapper.like("username",name);
		}

		//姓名关键词
		String Content = sysOperationLog.getLogContent();
		if(oConvertUtils.isNotEmpty(Content)) {
			queryWrapper.like("log_content",Content);
		}
		IPage<SysOperationLog> pageList = sysOperationLogService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param sysOperationLogPage
	 * @return
	 */
	@AutoLog(value = "操作日记-添加")
	@ApiOperation(value="操作日记-添加", notes="操作日记-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysOperationLogPage sysOperationLogPage) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		SysOperationLog sysOperationLog = new SysOperationLog();
		sysOperationLogPage.setCostTime( LocalDate.now().toString());
		sysOperationLogPage.setSerialNumber("NO."+String.valueOf(Calendar.getInstance().getTimeInMillis()));
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//设置IP地址
			sysOperationLogPage.setIp(IPUtils.getIpAddr(request));
		} catch (Exception e) {
			sysOperationLogPage.setIp("127.0.0.1");
		}
		//获取登录用户信息
		if(user==null){
			try {
				user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
		if(user!=null){
			sysOperationLogPage.setUserid(user.getUsername());
			sysOperationLogPage.setUsername(user.getRealname());
		}



		BeanUtils.copyProperties(sysOperationLogPage, sysOperationLog);
		sysOperationLogService.saveMain(sysOperationLog);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param sysOperationLogPage
	 * @return
	 */
	@AutoLog(value = "操作日记-编辑")
	@ApiOperation(value="操作日记-编辑", notes="操作日记-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SysOperationLogPage sysOperationLogPage) {
		SysOperationLog sysOperationLog = new SysOperationLog();
		BeanUtils.copyProperties(sysOperationLogPage, sysOperationLog);
		SysOperationLog sysOperationLogEntity = sysOperationLogService.getById(sysOperationLog.getId());
		if(sysOperationLogEntity==null) {
			return Result.error("未找到对应数据");
		}
		sysOperationLogService.updateMain(sysOperationLog);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "操作日记-通过id删除")
	@ApiOperation(value="操作日记-通过id删除", notes="操作日记-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		sysOperationLogService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "操作日记-批量删除")
	@ApiOperation(value="操作日记-批量删除", notes="操作日记-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.sysOperationLogService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "操作日记-通过id查询")
	@ApiOperation(value="操作日记-通过id查询", notes="操作日记-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SysOperationLog sysOperationLog = sysOperationLogService.getById(id);
		if(sysOperationLog==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(sysOperationLog);

	}
	

    /**
    * 导出excel
    *
    * @param request
    * @param sysOperationLog
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysOperationLog sysOperationLog) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<SysOperationLog> queryWrapper = QueryGenerator.initQueryWrapper(sysOperationLog, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<SysOperationLog> queryList = sysOperationLogService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<SysOperationLog> sysOperationLogList = new ArrayList<SysOperationLog>();
      if(oConvertUtils.isEmpty(selections)) {
          sysOperationLogList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          sysOperationLogList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<SysOperationLogPage> pageList = new ArrayList<SysOperationLogPage>();
      for (SysOperationLog main : sysOperationLogList) {
          SysOperationLogPage vo = new SysOperationLogPage();
          BeanUtils.copyProperties(main, vo);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "操作日记列表");
      mv.addObject(NormalExcelConstants.CLASS, SysOperationLogPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("操作日记数据", "导出人:"+sysUser.getRealname(), "操作日记"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<SysOperationLogPage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysOperationLogPage.class, params);
              for (SysOperationLogPage page : list) {
                  SysOperationLog po = new SysOperationLog();
                  BeanUtils.copyProperties(page, po);
                  sysOperationLogService.saveMain(po );
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }



}
